import os
import platform

env = DefaultEnvironment()
env['srcroot'] = env.Dir('.').abspath
dbg = ARGUMENTS.get('dbg', 0)
env['objroot'] = env.Dir('build/dbg').abspath
env['DEBUG'] = True
#build_info.update_build_info(env['objroot'])
objroot = env['objroot']
srcroot = env['srcroot']

if not os.path.isdir(objroot):
  os.system('mkdir %s' % srcroot + '/build')
  os.system('mkdir %s' % objroot)
#####################################

# make 3rd lib
#####################################
def execute_shell_script(script, ignore_error = False):
  script_file_name = '.shell_script'
  f = open(script_file_name, 'w')
  f.write(script);
  f.close()
  result_file_name = '.result'
  ret = os.system('cat %s|sh>%s 2>&1' % (script_file_name, result_file_name))
  if ret != 0 and not ignore_error:
    raise Exception('execute shell command failed, pls see detail in %s' % result_file_name)

def update_3rd():
  update_script = '''\
echo 'Export 3rd libraries'
path=%s
path=$(dirname $path)
echo $path
cd %s
cp $path/3rd/publish/3rd_packages_dbg.tgz .
check_ret 'export 3rd_packages failed'
rm -rf third_party_install
tar -xzf 3rd_packages_dbg.tgz
check_ret 'unpack 3rd_packages failed!!!'
rm -f 3rd_packages_dbg.tgz
''' % (env['srcroot'],
       env['objroot'])
  execute_shell_script(update_script)

def check_3rd_library():
  libpath = os.path.join(env['objroot'], 'third_party_install')
  return os.path.isdir(libpath)

with_up3rd = int(ARGUMENTS.get('up3rd', 0))

if with_up3rd or not check_3rd_library():
  print 'Download lasted 3rd library...'
  update_3rd()
else:
  print 'Check 3rd libraries ok.'
print '==================================================up3rd libs ok'
#################################
# protobuffer
################################


def ProtocolBufferEmitter(target, source, env):
  source1 = []
  target1 = []
  for s in source:
    s_abspath = s.abspath
    if not s_abspath.startswith(objroot):
      s_abspath = s_abspath.replace(srcroot, objroot)
    target_prefix = s_abspath[:s_abspath.find('.proto')]
    target1 += [
      target_prefix + ".pb.cc",
      target_prefix + ".pb.h"
    ]
    if os.path.isfile(s_abspath):
      output = s_abspath
    else:
      output = s_abspath.replace(env.Dir('$objroot').abspath,
                                 env.Dir('$srcroot').abspath)
    source1 += [output]
  return target1, source1

def LinuxProtocolBufferGenerator(source, target, env, for_signature):
  action = "export LD_LIBRARY_PATH=build/dbg/third_party_install/lib;$objroot/third_party_install/bin/protoc " + \
    "--proto_path=$srcroot " + \
    "--proto_path=$objroot/third_party_install/third_party/ " + \
    "--cpp_out=$objroot "
  for s in source:
    action += s.abspath + " "
  return action

linux_proto_builder = Builder(generator = LinuxProtocolBufferGenerator,
                       emitter = ProtocolBufferEmitter,
                        )
env['BUILDERS']['ProtocolBuffer'] = linux_proto_builder

#def ProtoLib(env, name):
#  proto_env = env.Clone()
#  proto_info = proto_env.ProtocolBuffer(name + '.proto')
#  proto_env.StaticLibrary(
#   target = name + '_pb',
#   source = [
#    proto_info[0].abspath,
#    proto_info[1].abspath]
#  )


#def ProtoGenerate(env, name) :
#  proto_env = env.Clone()
#  proto_info = proto_env.ProtocolBuffer(name + '.proto')

##################################################
#get libs
####################################################

#to find file has .h, reader in /usr/lib/scons
cpp_path = [
  '$objroot',
  '$srcroot',
  'objroot/third_party_install',
  'objroot/third_party_install/include',
  ]
lib_path = [
  '$objroot/third_party_install/lib',
  ]
static_libs = [
  'third_party_glog',
  'libprotoc.so',
  'libprotobuf.so',
  ]

env.Append(CPPFLAGS = ' -static -Wall -Werror -Wl,--eh-frame-hdr, -malign-double')
env.Append(CPPPATH = cpp_path)
env.Append(LIBPATH = lib_path)
env.Append(LIBS = static_libs)


subdir = ['cpp_file', 'proto']
Export('env')
for x in subdir:
  target_dir = '%s/%s' % (env['objroot'], x)
  SConscript('%s/SConscript' % (x), variant_dir = target_dir, duplicate = 0)
